package com.blaze.framework.core.cloud.http;

import com.blaze.framework.core.util.constants.Constants;
import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okio.Buffer;
import okio.BufferedSource;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * okhttp日志拦截器
 *
 * @author created by Zhou Zongbo on 2025/5/23.
 */
public class OkHttpLogInterceptor implements okhttp3.Interceptor {
    private static final Charset UTF8 = StandardCharsets.UTF_8;
    private static final String CONTENT_TYPE = "Content-Type";
    private final Logger logger;

    public OkHttpLogInterceptor(Logger logger) {
        this.logger = logger;
    }

    @org.jetbrains.annotations.NotNull
    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // 打印请求信息
        logRequest(request, chain.connection());

        long startTime = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            logger.log("<-- HTTP FAILED: {}" + e.getMessage());
            throw e;
        }
        long consumerTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

        // 打印响应信息
        return logResponse(response, consumerTime);
    }

    private void logRequest(Request request, Connection connection) throws IOException {
        boolean logBody = request.body() != null;
        boolean logHeaders = logBody || !request.headers().names().contains(CONTENT_TYPE);

        RequestBody requestBody = request.body();
        long contentLength = requestBody != null ? requestBody.contentLength() : -1;

        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;

        StringBuilder logBuilder = new StringBuilder();
        logBuilder.append("\n--> ").append(request.method()).append(' ').append(request.url()).append(' ').append(protocol).append('\n');

        if (logHeaders) {
            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                // Skip headers from the request body as they are explicitly logged above.
                if (!CONTENT_TYPE.equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                    logBuilder.append(name).append(": ").append(headers.value(i)).append('\n');
                }
            }
        }

        if (logBody && isPlaintext(requestBody)) {
            logBuilder.append(bodyToString(request));
        }

        logBuilder.append("--> END ").append(request.method());
        if (contentLength != -1) {
            logBuilder.append(" (").append(contentLength).append("-byte body)");
        }
        logBuilder.append('\n');

        logger.log(logBuilder.toString());
    }

    private Response logResponse(Response response, long tookMs) throws IOException {
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        ResponseBody responseBody = clone.body();
        boolean logBody = HttpHeaders.promisesBody(clone) && !"HEAD".equalsIgnoreCase(clone.request().method());

        StringBuilder logBuilder = new StringBuilder();
        logBuilder.append("<-- ")
                .append(clone.code())
                .append(' ')
                .append(clone.message())
                .append(' ')
                .append(clone.request().url())
                .append(" (").append(tookMs).append("ms)");

        if (logBody) {
            Headers headers = clone.headers();
            logBuilder.append('\n');
            for (int i = 0, count = headers.size(); i < count; i++) {
                logBuilder.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n');
            }
        }

        if (logBody && isPlaintext(responseBody)) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.getBuffer();

            if (isPlaintext(buffer)) {
                logBuilder.append(buffer.clone().readString(getContentCharset(responseBody))).append('\n');
            } else {
                logBuilder.append("<-- END HTTP (binary ").append(buffer.size()).append("-byte body omitted)\n");
            }
        } else {
            logBuilder.append("<-- END ");
            if (Objects.nonNull(responseBody)) {
                logBuilder.append("HTTP (").append(responseBody.contentLength()).append("-byte body)\n");
            }
        }

        logger.log(logBuilder.toString());
        return response;
    }

    private static Charset getContentCharset(ResponseBody responseBody) {
        Charset charset = null;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        if (charset == null) {
            charset = UTF8;
        }
        return charset;
    }

    private static boolean isPlaintext(RequestBody body) {
        if (body == null) {
            return false;
        }
        MediaType mediaType = body.contentType();
        return mediaType != null && (mediaType.type().equals("text") || isProbablyUtf8(mediaType));
    }

    private static boolean isPlaintext(ResponseBody body) {
        if (body == null) {
            return false;
        }
        MediaType mediaType = body.contentType();
        return mediaType != null && (mediaType.type().equals("text") || isProbablyUtf8(mediaType));
    }

    private static boolean isPlaintext(Buffer buffer) {
        try (Buffer prefix = new Buffer()) {
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private static boolean isProbablyUtf8(MediaType mediaType) {
        Charset charset = mediaType.charset(UTF8);
        if (Objects.isNull(charset)) {
            return false;
        }
        return Constants.UTF_8.toLowerCase().equalsIgnoreCase(charset.name());
    }

    private static String bodyToString(Request request) {
        try (Buffer buffer = new Buffer()) {
            final Request copy = request.newBuilder().build();
            if (copy.body() != null) {
                copy.body().writeTo(buffer);
            } else {
                return "";
            }
            return buffer.readString(UTF8);
        } catch (final IOException e) {
            return "读取请求报文异常";
        }
    }

    public interface Logger {
        void log(String message);
    }
}
